package hsb.ruoyi.common.config.security;

import com.usthe.sureness.subject.Subject;
import com.usthe.sureness.subject.SubjectCreate;
import com.usthe.sureness.util.SurenessConstant;
import hsb.ruoyi.common.core.domain.TokenService;
import hsb.ruoyi.common.core.domain.model.JwtSubject;
import hsb.ruoyi.common.core.domain.model.LoginUser;
import hsb.ruoyi.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.inject.Inject;
import javax.inject.Singleton;
import javax.ws.rs.container.ContainerRequestContext;

/**
 * @author 胡帅博
 * @date 2023/1/2 16:09
 */
@Singleton
public class JwtSubjectJaxRsCreator implements SubjectCreate {

    private static final Logger logger = LoggerFactory.getLogger(com.usthe.sureness.subject.creater.JwtSubjectJaxRsCreator.class);

    @Inject
    TokenService tokenService;

    @Override
    public boolean canSupportSubject(Object context) {

        if (context instanceof ContainerRequestContext) {
            String authorization = getAuthorization((ContainerRequestContext) context);

            return authorization != null && authorization.length() > 0;

            //  if (authorization != null && authorization.startsWith(SurenessConstant.BEARER)) {
            // String jwtValue = authorization.replace(SurenessConstant.BEARER, "").trim();
            // return !JsonWebTokenUtil.isNotJsonWebToken(jwtValue);

        }
        //  }
        return false;
    }

    @Override
    public Subject createSubject(Object context) {
        String authorization = getAuthorization((ContainerRequestContext) context);
        if (authorization != null && authorization.length() > 0) {
            //拿不到就说明jwt失效
            //JwtSubject bindSubject = (JwtSubject) SurenessContextHolder.getBindSubject();


            JwtSubject bindSubject = getSubject(authorization);
            String requestUri = ((ContainerRequestContext) context).getUriInfo().getPath();
            String requestType = ((ContainerRequestContext) context).getMethod();
            String targetUri = requestUri.concat("===").concat(requestType.toLowerCase());

            if (bindSubject == null) {
                //bindSubject是null则说明，当前用户的jwt已经失效了
                // bindSubject = JwtSubject.builder(authorization).setTargetResource(targetUri).build();
            } else {
                bindSubject.setTargetResource(targetUri);
            }
            return bindSubject;
        }
        return null;
    }

    private JwtSubject getSubject(String authorization) {
        Subject subject = tokenService.geSubject(authorization);
        if (StringUtils.isNotNull(subject)) {
            tokenService.verifyToken((LoginUser) subject.getPrincipal());
            SurenessContextHolder.bindSubject(subject);
            return (JwtSubject) subject;
        }
        return null;
    }

    private String getAuthorization(ContainerRequestContext request) {
        String authorization = request.getHeaderString(SurenessConstant.AUTHORIZATION);

        if (authorization == null || authorization.length() == 0) {
            //考虑是从websocket建立的连接，这时候请求头中不会包含Authorization字段，所以尝试从请求参数中获取
            Object property = request.getProperty(SurenessConstant.AUTHORIZATION);
            if (property instanceof String) {
                authorization = (String) property;
            }
        }
        return authorization;
    }


}